package com.itheima.service.impl;

import com.itheima.bean.Course;
import com.itheima.bean.User;
import com.itheima.context.BaseContext;
import com.itheima.mapper.CourseMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.service.CourseService;
import lombok.extern.slf4j.Slf4j;
import netscape.javascript.JSObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class CourseServiceImpl implements CourseService {

    private static final String KEY = "Course";

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CourseMapper courseMapper;
    /**
     * 查询学科
     *
     * @return
     */
    @Override
    public List<Course> getCourseInfo() {
        List<Course> courseList = courseMapper.getCourseInfo();
        //使用redisTemplate缓存
        redisTemplate.opsForValue().set(KEY,courseList);
        return courseList;
    }

    /**
     * 添加学科
     *
     * @param course
     */
    @Override
    public void addCourse(Course course) {
       //获取用户id
        Long userId = BaseContext.getCurrentId();
        //补充基础属性
        course.setCreateUser(userId.intValue());
        course.setUpdateUser(userId.intValue());
        course.setCreateTime(LocalDateTime.now());
        course.setUpdateTime(LocalDateTime.now());
        List<Course> courseList = (List<Course>) redisTemplate.opsForValue().get(KEY);
        if(courseList != null && !courseList.isEmpty()) {
            courseList.forEach(course1 -> {
                if(course1.getName().equals(course.getName())) {
                    log.info("课程已经存在,不能添加");
                }
            });
        }
        //添加 + 修改 + 删除都直接先清空缓存，在进行缓存
        //清空缓存
        redisTemplate.delete(KEY);
        //新增课程
        courseMapper.insert(course);
        courseList.add(course);
    }
}
